#include "g_headers.h"
#include <stdio.h>
#include <cstdlib>
#include <unistd.h>
#include <QErrorMessage>
using namespace std;

int connect_server(int& sock, struct sockaddr_in& srv_add)
{
    if( ( sock = socket(AF_INET,SOCK_STREAM,0)) < 0 )
    {
        QErrorMessage err_msg;
        err_msg.setWindowTitle("Error:");
        err_msg.showMessage("socket function failed");
        err_msg.exec();

        return -1;
    }

    if ( ::connect(sock,(struct sockaddr*)&srv_add,
                            sizeof(srv_add)) < 0 )
    {
        QErrorMessage err_msg;
        err_msg.setWindowTitle("Error:");
        err_msg.showMessage("Can't connect to the server");
        err_msg.exec();

        return -1;
    }

    return 0;
}

void file_copy(int des, int src)
{
	int res;
	char buf[BUF_SIZ];

	while( (res = readn(src,buf,BUF_SIZ)) > 0 )
	{
		Writen(des,buf,res);
	}

	if( res == 0 )
	{
		return;
	} 
	else
	{
		perror("read");
		exit(-1);
	}
}

//带计数的文件接收例程
void file_rcv(int des, int src)
{
	int res,num;
	char buf[BUF_SIZ];

	while(true)
	{
		res = readn(src,&num,sizeof(int));
		if( res <= 0 )
			break;
		if( num == 0 )    //文件尾
			return;

		res = readn(src,buf,num);
		if(res <= 0)
			break;

		Writen(des,buf,res);
	}

	if( res == 0 )
	{
		perror("连接提前关闭");
		exit(-1);
	} 
	else
	{
		perror("read");
		exit(-1);
	}
}
